#include "magicstring.h"

using std::string;
using std::map;

bool MagicString::hasVar(string const & var) const
{
	size_t found;
	string tmp = '%' + var;
	found = str_.find(tmp);
	if (found != string::npos)
		return true;
	return false;
}

bool MagicString::setValue(string const & var, int value)
{
	if (!hasVar(var))
		return false;
	values_[var] = value;
	return true;
}

string MagicString::toString() const
{
	string var;
	int val;
	char valstr[10];
	size_t found;
	string result(str_);
	map<string, int>::const_iterator it = values_.begin();
	for ( ; it != values_.end(); ++it)
	{
		var = '%' + it->first;
		val = it->second;
		sprintf_s(valstr, "%d", val);
		found = result.find(var);
		result.replace(found, var.size(), valstr);
	}
	size_t n;
	found = result.find('{');
	while (found != string::npos)
	{
	    n = 0;
	    while (result[found+n] != '}')
	    {
	        ++n;
	    }
	    result.erase(found, n+1);
	    found = result.find('{');
	}
	return result;
}